<?php

/**
 * 视图
 */

namespace wtfphp\libs;

class view {
    //文件路径
    private $_filename = '';

    //变量
    private $_data = array();

    //缓存开关
    private $_isCache = false;

    //缓存路径
    private $_cacheFile = '';

    //缓存目录
    private $_cacheDir = '';

    /**
     * 设置文件路径
     * 不包含后缀
     */
    function setFile($filename) {
        $suffix = '.php';   //固定后缀
        $this->_filename = $filename . $suffix;
    }

    /**
     * 传值
     */
    function setVar($name, $value) {
        $this->_data[$name] = $value;
    }

    /**
     * 加载
     */
    function load() {
        //检测
        if (!is_file($this->_filename)) {
            throw new \Exception("[" . $this->_filename . "] is not a file!");
        }
        //传值
        extract($this->_data);
        unset($this->_data);
        //加载
        include $this->_filename;
        //缓存
        $this->doCache();
        exit;
    }

    /**
     * 设置缓存目录
     */
    function setCacheDir($dir) {
        $this->_cacheDir = $dir;
    }

    /**
     * 开启缓存
     * @param $time 时间：秒
     * @param $cid  缓存id
     */
    function cache($time = 300, $cid = '') {
        if (!$this->_cacheDir) {
            throw new \Exception("[" . $this->_cacheDir . "] must be set!");
        }
        $this->_isCache = true;
        //cid
        if (empty($cid)) {
            $cid = md5('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        }
        //读取缓存
        $this->_cacheFile = $this->_cacheDir . $cid . '.html';
        if (is_file($this->_cacheFile)) {
            $endTime = filemtime($this->_cacheFile) + $time;
            if ($endTime > time()) {
                readfile($this->_cacheFile);
                exit;
            }
        }
    }

    /**
     * 生成缓存
     */
    private function doCache() {
        if (!$this->_isCache) {
            return false;
        }
        //创建目录
        $dir = dirname($this->_cacheFile);
        if (!is_dir($dir)) {
            mkdir($dir, 0766, true);
        }
        //生成html
        return file_put_contents($this->_cacheFile, ob_get_contents());
    }
}